// document.addEventListener('plusready', onPlusReady, false);
var r = null;
var url = '';
import store from '@/vuex/store'

var route = '_doc/audio/';//存放音频
var server = store.state.ip+'/hi/sayhi';//服务器地址
// var server='http://182.151.105.165:16000/elderly/chat/publishchat';//服务器地址
var files = [];
//录取音频
// function onPlusReady() {
//   r = plus.audio.getRecorder();
// }
function startReady() {
  r = plus.audio.getRecorder()
  if (r == null) {
    alert('未准备好')
    r = plus.audio.getRecorder()
    return
  }
  r.record({filename: route}, function (p) {
    plus.io.resolveLocalFileSystemURL(p, function (entry) {
      files.push({
        path: entry.toLocalURL(),
        name: entry.name
      });
      upload();//H5上传语音
    }, function (e) {

    })
  }, function (e) {
    alert('录制失败' + e.message)
  })
}

//转base64编码格式
function base64(url) {
  plus.io.resolveLocalFileSystemURL(url, function (entry) {
    entry.file(function (file) {
      let fileReader = new plus.io.FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onloadend = function (p) {
        let imgbase64 = p.target.result.toString();
        store.commit("base64",imgbase64)
        return imgbase64
      }
    })
  });
};

//停止录音
function stopReady() {
  r.stop()
}

//播放音频

function startPlay(url) {
  var p = plus.audio.createPlayer(url);
// alert(url)

  setTimeout(() => {
    let len = p.getDuration() //音频长度、单位s
  }, 500);

  p.play()
}


// 上传文件
function upload() {
  if (files.length <= 0) {
    plus.nativeUI.alert("没有添加上传文件！");
    return;
  }

  var wt = plus.nativeUI.showWaiting();
  var task = plus.uploader.createUpload(server,
    {method: "POST"},
    function (t, status) { //上传完成
      let te = JSON.parse(t.responseText)
      console.log(t,te)
      if (status == 200) {
        startPlay
        files = [];
        wt.close();
      } else {
        files = []
        wt.close();
      }
    }
  );
  task.addData('userId', localStorage.userid);
  task.addData('text', '');
  task.addData('lng', store.state.locations.lng.toString());
  task.addData('lat', store.state.locations.lat.toString());
  // console.log(JSON.toString(store.state.locations.lng))
  // console.log(files[0].path)
  for (var i = 0; i < files.length; i++) {
    var f = files[i];
    task.addFile(f.path, {key: 'file'});
  }
  task.setRequestHeader("authorization", localStorage.userid + '_' + store.state.token);
  task.start();
}



//往页面传函数方法
export default {
  stopReady,//使用touchend事件调用
  startReady,//使用touchstart事件调用
  startPlay,//播放语音
  upload
}
